use hello::ThreadPool;
use std::{
    fs,
    io::{BufRead, BufReader, Write},
    net::{TcpListener, TcpStream},
    thread,
    time::Duration,
};
fn main() {
    let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
    let pool = ThreadPool::new(4);
    for stream in listener.incoming().take(2) {
        let stream = stream.unwrap();
        //thread::spawn(|| handle_connection(stream));
        pool.execute(|| handle_connection(stream));
    }
    println!("Shutting down.");
}
fn handle_connection(mut stream: TcpStream) {
    println!("handle_connection:executed");
    let buf_reader = BufReader::new(&stream);
    let mut request_line = String::from("nothing");
    let mut status_line = "HTTP/1.1 404 NOT FOUND";
    let mut filename = "404.html";
    // 持续读取直到获取非空行
    for line in buf_reader.lines() {
        match line {
            Ok(request) if !request.is_empty() => {
                println!("match Request: {}", request);

                let (in_status_line, in_filename) = match &request[..] {
                    "GET / HTTP/1.1" => ("HTTP/1.1 200 OK", "hello.html"),
                    "GET /sleep HTTP/1.1" => {
                        thread::sleep(Duration::from_secs(5));
                        ("HTTP/1.1 200 OK", "hello.html")
                    }
                    _ => ("HTTP/1.1 404 NOT FOUND", "404.html"),
                };
                status_line = in_status_line;
                filename = in_filename;
                request_line = request;
                break; // 获取到有效请求后退出循环
            }
            Ok(_) => {
                println!("OK(_)");
                continue;
            } // 空行继续等待
            Err(e) => {
                println!("ERR");
                eprintln!("Error reading line: {}", e);
                continue; // 读取错误继续等待
            }
        }
    }
    //let request_line = buf_reader.lines().next().unwrap().unwrap();
    //let request_line = buf_reader.lines().next().unwrap().unwrap();
    //let http_request: Vec<_> = buf_reader
    //    .lines()
    //    .map(|line| line.unwrap())
    //    .take_while(|line| !line.is_empty())
    //    .collect();

    //let request_line = http_request.get(0).unwrap();

    //let (status_line, filename) = match &request_line[..] {
    //    "GET / HTTP/1.1" => ("HTTP/1.1 200 OK", "hello.html"),
    //    "GET /sleep HTTP/1.1" => {
    //        thread::sleep(Duration::from_secs(5));
    //        ("HTTP/1.1 200 OK", "hello.html")
    //    }
    //    _ => ("HTTP/1.1 404 NOT FOUND", "404.html"),
    //};
    let contents = fs::read_to_string(filename).unwrap();
    let length = contents.len();
    let response = format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}");

    println!("Response: {status_line:#?}");
    println!("Request: {request_line:#?}");

    if request_line == "nothing" {
        return;
    }

    stream.write_all(response.as_bytes()).unwrap();
}
